package cn.lyq.card.ui.wallet

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import cn.lyq.card.R
import cn.lyq.card.base.BaseDialogFg
import cn.lyq.card.global.BusTag
import cn.lyq.card.utils.setClick
import cn.lyq.card.utils.toMoney
import com.blankj.utilcode.util.BusUtils
import com.blankj.utilcode.util.KeyboardUtils
import kotlinx.android.synthetic.main.dialog_cash_pwd.*


class CashPwdFg(override val rootId: Int = R.layout.dialog_cash_pwd) : BaseDialogFg() {

    private val money by lazy {
        arguments?.getDouble(KEY_MONEY, 0.0) ?: 0.0
    }
    private val type by lazy {
        arguments?.getInt(KEY_TYPE, 0) ?: 0
    }


    companion object {
        private const val KEY_MONEY = "MONEY"
        private const val KEY_TYPE = "TYPE"

        fun newInstance(money: Double, currentItem: Int): CashPwdFg {
            val args = Bundle()
            args.putDouble(KEY_MONEY, money)
            args.putInt(KEY_TYPE, currentItem)
            val fragment = CashPwdFg()
            fragment.arguments = args
            return fragment
        }
    }

    private val circleList by lazy {
        arrayOf(
            tvInput0, tvInput1, tvInput2,
            tvInput3, tvInput4, tvInput5
        )
    }

    override fun initView(view: View) {
        super.initView(view)
        KeyboardUtils.showSoftInput(etPwd)

        tvMoney.text = "￥ ${money.toMoney()}"
    }

    override fun initListener(view: View) {
        super.initListener(view)
        imgBack.setClick {
            KeyboardUtils.hideSoftInput(etPwd)
            dismiss()
        }
        etPwd.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                val value = s.toString()
                changeCircle(value.length)
                if (value.length == 6){
                    BusUtils.post(BusTag.CASH_APPLY, Triple(money, value, type))
                    KeyboardUtils.hideSoftInput(etPwd)
                    dismiss()
                }
            }

        })
        bg.setClick {
            KeyboardUtils.showSoftInput(etPwd)
        }
    }

    private fun changeCircle(length: Int) {
        circleList.withIndex().forEach {
            it.value.visibility = if (length > it.index) View.VISIBLE else View.INVISIBLE
        }
    }
}